package com.cos.controller.admin.dynamic;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.cos.controller.base.BaseController;
import com.cos.entity.Page;
import com.cos.entity.system.User;
import com.cos.service.admin.dynamic.CompanyCircleService;
import com.cos.service.admin.dynamic.DynamicImgService;
import com.cos.util.AppUtil;
import com.cos.util.Const;
import com.cos.util.DateUtil;
import com.cos.util.FileUpload;
import com.cos.util.Jurisdiction;
import com.cos.util.PageData;
import com.cos.util.PathUtil;
import com.cos.util.StringUtil;
import com.cos.util.Tools;
import com.cos.util.Watermark;

@Controller
@RequestMapping(value="/companyDynamic")
public class CompanyDynamicController extends BaseController{
	
	/**
	 * 菜单地址url(权限用)
	 */
	String menuUrl = "companyDynamic/listDynamic.do";
	
	@Autowired
	private CompanyCircleService companyCircleService ;
	@Autowired
	private DynamicImgService dynamicImgService ;
	/**
	 * 针对公司个人
	 * @param page
	 * @return
	 */
	@RequestMapping(value="/list")
	public ModelAndView list(Page page){
		logBefore(logger, "内容分类列表");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		pd.put("C_ID",session.getAttribute("C_ID").toString() );
		try{
			pd = this.getPageData();
			page.setPd(pd);
			List<PageData>	varList = companyCircleService.getInforTypeList(pd) ;	//列出列表
			mv.setViewName("admin/informationType/informationTypeList");
			mv.addObject("varList", varList);
			mv.addObject("pd", pd);
			mv.addObject(Const.SESSION_QX,this.getHC());	//按钮权限
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	/**
	 * 获取该公司所发布的所有动态信息
	 * @param page
	 * @return
	 */
    @RequestMapping(value="/listDynamic")
	public ModelAndView listDynamic(Page page){
		logBefore(logger, "某一个企业下面的动态列表");
		List<PageData>	varList = new ArrayList<PageData>() ;
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			String C_ID = session.getAttribute("C_ID").toString() ;
			pd.put("ID",C_ID);
			pd = this.getPageData();
			page.setPd(pd);
			varList = companyCircleService.getDynamicById(C_ID) ;	//列出列表
			mv.setViewName("admin/dynamic/dynamicList");
			mv.addObject("varList", varList);
			mv.addObject("pd", pd);
			mv.addObject(Const.SESSION_QX,this.getHC());	//按钮权限
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	/**
	 * 跳转到发布动态信息的页面
	 */
	@RequestMapping(value="/goToDynamic")
	public ModelAndView goToDynamic() throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		//获取该公司的内容分类
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		pd.put("C_ID",session.getAttribute("C_ID") );
		List<PageData> list = companyCircleService.getInforTypeList(pd) ;
		mv.setViewName("admin/dynamic/addDynamic");
		mv.addObject("pd", pd);
		mv.addObject("list",list) ;
		return mv;
	}
	/**
	 * 发布动态
	 * @param response 
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/addDynamic")
	public Object addDynamic(Page page) throws Exception{
		logBefore(logger, "添加动态");
		Map<String,String> map = new HashMap<String,String>();
		PageData pd = new PageData();
		String[] IDS = null ; //获取已经选择的分类
		String[] newIds =null ;//自定义内容分类的id
		String[] CI_IDs = null ;
		List<PageData> pageDatas = new ArrayList<PageData>() ;
		List<PageData> pageDatass = new ArrayList<PageData>() ;
		if(Jurisdiction.buttonJurisdiction(menuUrl, "add")){
		try{
			Subject currentUser = SecurityUtils.getSubject();  
			Session session = currentUser.getSession();
			String C_ID = session.getAttribute("C_ID").toString() ;
			pd = this.getPageData();
			pd.put("C_ID",C_ID ) ;
			page.setPd(pd);
			List<PageData> companyList = new ArrayList<PageData>();
			//判断该公司是否自己创建自己的内容分类
			String infoType = pd.getString("infoType") ;
			if(infoType!=null && !infoType.equals("")) {
				String info[] = StringUtil.StrList(infoType) ;
				for(int i=0;i<info.length;i++) {
					PageData p = new PageData();
					pd.put("STATUS",1 ) ;
					pd.put("PARENT_ID", 0) ;
					pd.put("NAME", info[i]) ;
					pd.put("ID", this.get32UUID() ) ;
					pageDatas.add(p) ;
					//添加公司自己定义的内容分类
					companyCircleService.saveInformationType(pd);
				}
			}
			//获取已经选择的内容类别
			String ids = pd.getString("typeIDs") ;
			if(null != ids && !"".equals(ids)){
				IDS = StringUtil.StrList(ids) ;
			}
			//获取自己添加的内容分类
			if(pageDatas.size()>0) {
				String[] idss = companyCircleService.groupIDs(pageDatas) ;
				//将两个分类 合并
				newIds = (String[]) ArrayUtils.addAll(IDS, idss) ;
			} else {
				newIds = IDS ;
			}
			//添加数据到中间表company_info_type
			for(int i=0;i<newIds.length;i++) {
				PageData pd_ = new PageData() ;
				pd_.put("ID", this.get32UUID()) ;
				pd_.put("I_ID", newIds[i]) ;
				pd_.put("C_ID", C_ID) ;
				pageDatass.add(pd_) ;
				companyCircleService.saveCompanyInfoType(pd_); 
			}
			//添加动态信息
			String D_ID = this.get32UUID() ;
			pd.put("ID", D_ID) ;
			pd.put("TIME", Tools.date2Str(new Date())) ;
			pd.put("SUPPORT_NUM  ", 0) ;
			pd.put("TRAMPLE_NUM  ", 0) ;
			pd.put("IS_RECOMMEND", 0) ;
			companyCircleService.saveDynamic(pd);
			//将D_ID放到session里面供添加图片使用
			session.setAttribute("D_ID", D_ID); 
			//获取刚才添加company_info_type数据的id
			CI_IDs = companyCircleService.groupIDs(pageDatass) ;
			//添加数据到中间表Dynamic_company_info_type
			for(int i=0;i<CI_IDs.length;i++) {
				PageData pd_ = new PageData() ;
				pd_.put("ID", this.get32UUID()) ;
				pd_.put("CI_ID", CI_IDs[i]) ;
				pd_.put("D_ID", D_ID) ;
				pageDatass.add(pd_) ;
				companyCircleService.saveDynamicCompanyInfoType(pd_);
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.toString()) ;
		}finally{
			logAfter(logger);
		}
		}
		map.put("result", "ok") ;
		return  AppUtil.returnObject(pd, map);
	}
	@RequestMapping(value="/addPicture")
	public ModelAndView addPicture(@RequestParam(required=false)MultipartFile[] file) throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		String C_ID = session.getAttribute("C_ID").toString() ;
		String D_ID = session.getAttribute("D_ID").toString();
		//获取添加的图片
		String  ffile = DateUtil.getDays(), fileName = "";
		if (null != file && file.length != 0) {
			int type_id = 0 ;
			
			for(MultipartFile f:file) {
				if(f.getSize() != 0) {
					//上传路径
					String filePath = PathUtil.getClasspath() + Const.FILEPATHIMG + ffile;		//文件上传路径
					//数据库中保存的文件名（即文件真是名）
					fileName = FileUpload.fileUp(f, filePath, this.get32UUID());	
					pd.put("ID", this.get32UUID());			//主键
					pd.put("C_ID", C_ID);					//公司id
					pd.put("D_ID", D_ID);					//动态id
					pd.put("URL", ffile + "/" + fileName);	//路径
					//保存图片信息
					dynamicImgService.save(pd);
					type_id++;
				}
			}
			pd.put("TYPE_ID", type_id) ;
			companyCircleService.editByID(pd);
		}else{
			System.out.println("上传失败");
		}
		mv.setViewName("save_result");
		return mv ;
	}
	
	/* ===============================权限================================== */
	public Map<String, String> getHC(){
		Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
		Session session = currentUser.getSession();
		return (Map<String, String>)session.getAttribute(Const.SESSION_QX);
	}
	/* ===============================权限================================== */
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));
	}
}
